package com.brooks.demo;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReentrantReadWriteLock 读写锁
 *
 * @Author mihutu
 * @Date 2020/10/19 10:05
 * @Version 1.0
 */
public class DemoReadWriteLock {
//    static Lock lock = new ReentrantLock();
    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock){
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("读完了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock,int val){
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("写完了"+val);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Runnable readL = ()-> read(readLock);
        Runnable writeL = ()-> write(writeLock, new Random().nextInt());
        for(int i=0;i<18;i++){
            new Thread(readL).start();
        }
        for(int i=0;i<2;i++){
            new Thread(writeL).start();
        }
    }

}
